<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use App\Http\Repositories\BaseRepository;
use App\Models\Admin\Models\MemberModel;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Closure;
use Illuminate\Support\Facades\Redis;

class Authenticate
{
    const CACHE_KEY = 'purchase:mediation:token:';
    const REDIS_KEY = 'Admin:member:';
    /**
     * 授权中间件
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws ApiException
     */
    public function handle(Request $request, Closure $next)
    {
        //获取token
        $token = $request->header('token','');
        if (empty($token)) {
            $token = $request->input('token',"");
            if(empty($token)){
                throw new ApiException(ApiException::ERROR_AUTHORIZATION);
            }
        }
        $token = str_replace(' ','',$token);

        //先从缓存 获取 token 的用户信息 如果不存在 再调用 获取用户信息
        $info = json_decode(Redis::get(self::REDIS_KEY.$token), true);
        if(!$info){
            $info = ((new MemberModel())->getInfoWithToken($token))->toArray();
            if (!$info) {
                throw new ApiException(ApiException::ERROR_AUTHORIZATION);
            }
            $info = Redis::setex(self::REDIS_KEY.$token, 3600, json_encode($info));
            app('config')->set(['userInfo' => $info]);

        } else {
            app('config')->set(['userInfo' => $info]);
        }

        app('config')->set(['pageSize'=> $request->input("pageSize", config('pageSize'))]);
        app('config')->set(['token'=> $token]);
        $response = $next($request);
        return $response;
    }
}
